package com.longcheer.weibo.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.weibo.net.WeiboException;

public class Utils {
    private static Map<String, SimpleDateFormat> formatMap = new HashMap<String, SimpleDateFormat>();
    
    public static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    public static boolean isEmpty(String str) {
        return (str == null || str.length() == 0) ? true : false;
    }
    
    public static Date parseDate(String str, String format) throws WeiboException{
        if (isEmpty(str)) {
            return null;
        }
        
        SimpleDateFormat sdf = formatMap.get(format);
        if (null == sdf) {
            sdf = new SimpleDateFormat(format, Locale.ENGLISH);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            formatMap.put(format, sdf);
        }
        try {
            synchronized(sdf){
                // SimpleDateFormat is not thread safe
                return sdf.parse(str);
            }
        } catch (ParseException pe) {
            throw new WeiboException("Unexpected format(" + str + ") returned from sina.com.cn");
        }
    }
    
    public static int getInt(String key, JSONObject json) throws JSONException {
        if (json.has(key)) {
            String str = json.getString(key);
            if(isEmpty(str) ||"null".equals(str)){
                return -1;
            }
            return Integer.parseInt(str);
        }
        
        return -1;
    }

    public static long getLong(String key, JSONObject json) throws JSONException {
        if (json.has(key)) {
            String str = json.getString(key);
            if (isEmpty(str) || "null".equals(str)) {
                return -1;
            }
            return Long.parseLong(str);
        }
        
        return -1;
    }
    
    public static boolean getBoolean(String key, JSONObject json) throws JSONException {
        if (json.has(key)) {
            String str = json.getString(key);
            if (isEmpty(str) || "null".equals(str)) {
                return false;
            }
            return Boolean.valueOf(str);
        }
        
        return false;
    }
    
    public static String getExpandNameFromURL(String url) {
        String[] array = url.split("\\.");
        if (array.length > 2) {
            return array[array.length-1];
        }
        
        return null;
    }
}
